<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="listQuery" size="small">
        <el-form-item>
          <el-input
            v-model="listQuery.name"
            placeholder="律师函编号/委托人/当事人"
            clearable
            @keyup.enter.native="handleFilter"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="listQuery.search_date"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-search"
            @click.native="handleFilter"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="handleAdd"
            >新增{{ this.title }}</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        :data="letters"
        border
        v-loading="listLoading"
        fit
        size="small"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          type="index"
          label="#"
          align="center"
        ></el-table-column>
        <el-table-column
          v-for="column in tableColumns"
          :key="column.key"
          :label="column.title"
          :prop="column.key"
          align="center"
          :width="column.width ? column.width : ''"
          :formatter="dataFormatter"
        ></el-table-column>
        <el-table-column
          align="left"
          label="操作"
          :width="is_super ? '290px' : '200px'"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleEdit(scope)"
              v-if="scope.row.stamp_confirm != 1"
              >编辑</el-button
            >
            <el-button
              type="success"
              size="mini"
              icon="el-icon-search"
              @click="handleEdit(scope)"
              v-else
              >查看</el-button
            >
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-printer"
              @click="handlePrint(scope.row)"
              v-if="scope.row.apply_confirm == 1"
              >打印</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="handleDelete(scope)"
              v-if="scope.row.apply_confirm != 1 || is_super == true"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getLetterList"
      />
    </el-card>
    <!-- 对话框表单 -->
    <el-dialog :visible.sync="dialogVisible" :title="getTitle" width="800px">
      <el-form
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="案件编号" prop="case">
              <el-select
                v-model="form.case"
                placeholder="案件编号"
                clearable
                @change="caseChange"
                :disabled="dialogType == 'edit'"
              >
                <el-option
                  v-for="item in cases"
                  :label="item.code"
                  :value="item.id"
                  :key="item.id"
                >
                  <span
                    >{{ item.code }}----[{{ item.client }} |
                    {{ item.party }}]</span
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="律所函编号" prop="code">
              <el-input
                type="text"
                v-model="form.code"
                placeholder="律所函编号"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="委托人" prop="client">
              <el-input
                type="text"
                v-model="form.client"
                placeholder="委托人"
                clearable
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当事人" prop="party">
              <el-input
                v-model="form.party"
                placeholder="当事人"
                clearable
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              v-if="form.case_type == 2 || form.case_type == 5"
              label="罪 名"
              prop="reason"
            >
              <el-input
                v-model="form.reason"
                placeholder="罪名"
                clearable
                disabled
              />
            </el-form-item>
            <el-form-item v-else label="案 由" prop="reason">
              <el-input
                v-model="form.reason"
                placeholder="案由"
                clearable
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审 级" prop="level">
              <el-input
                v-model="form.level"
                placeholder="审级"
                clearable
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="律 师" prop="lawyer">
              <el-input
                v-model="form.lawyer"
                placeholder="律师"
                clearable
                :disabled="form.stamp_confirm == true && form.code != ''"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="针对机关" prop="court">
              <el-input
                v-model="form.court"
                placeholder="法院/检察院/看守所等"
                clearable
                :disabled="form.stamp_confirm == true && form.code != ''"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="申请确认" prop="apply_confirm">
              <el-radio-group
                v-model="form.apply_confirm"
                :disabled="form.apply_time != null"
              >
                <el-radio :label="true">确定</el-radio>
                <el-radio :label="false">暂不</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          v-if="form.stamp_confirm != 1"
          @click="handleSave(false)"
          >保存</el-button
        >
        <el-button
          type="primary"
          @click="handleSave(true)"
          v-if="form.stamp_confirm != 1"
          >保存并打印</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  getLetters,
  addLetter,
  updateLetter,
  delLetter,
  getAllCases,
} from "@/api/case";
import { formatDateTime } from "@/utils/datetime";
import Pagination from "@/components/Pagination";

const defaultForm = {
  id: null,
  code: "",
  case: null,
  court: "",
  client: "",
  party: "",
  lawyer: null,
  reason: "",
  apply_confirm: null,
  user: null,
  case_type: null,
  level: "",
};

export default {
  name: "Letter",
  data() {
    const checkReason = (rule, value, callback) => {
      if (value === "") {
        if (this.case_type == 2 || this.case_type == 5) {
          callback(new Error("请输入罪名"));
        } else {
          callback(new Error("请输入案由"));
        }
      } else {
        callback();
      }
    };

    return {
      form: Object.assign({}, defaultForm),
      formRules: {
        case: [{ required: true, message: "请选择案件", trigger: "blur" }],
        client: [
          {
            type: "string",
            required: true,
            message: "请输入委托人",
            trigger: "blur",
          },
        ],
        party: [
          {
            type: "string",
            required: true,
            message: "请输入当事人",
            trigger: "blur",
          },
        ],
        reason: [
          {
            type: "string",
            required: true,
            validator: checkReason,
            trigger: "blur",
          },
        ],
        court: [
          {
            type: "string",
            required: true,
            message: "请输入针对机关",
            trigger: "blur",
          },
        ],

        lawyer: [
          {
            type: "string",
            required: true,
            message: "请输入律师",
            trigger: "blur",
          },
        ],
        level: [
          {
            type: "string",
            required: true,
            message: "请输入审级",
            trigger: "blur",
          },
        ],
        apply_confirm: [
          {
            type: "boolean",
            required: true,
            message: "请选择申请确认",
            trigger: "blur",
          },
        ],
      },
      tableColumns: [
        {
          key: "code",
          title: "律所函编号",
        },
        {
          key: "case_name",
          title: "案件编号",
        },
        // {
        //   key: "client",
        //   title: "委托人",
        // },
        {
          key: "party",
          title: "当事人",
        },
        // {
        //   key: "reason",
        //   title: "案由/罪名",
        // },
        {
          key: "apply_time",
          title: "申请时间",
        },
        {
          key: "stamp_time",
          title: "盖章时间",
        },
      ],
      title: "律所函",
      dialogVisible: false,
      dialogType: "new",
      letters: [],
      cases: [],
      case_type: null,
      case_types: [
        { id: 1, name: "民事" },
        { id: 2, name: "刑事" },
        { id: 3, name: "行政" },
        { id: 4, name: "刑附民" },
        { id: 5, name: "刑事自诉" },
      ],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 15,
        name: null,
        search_date: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["uid", "is_super"]),
    getTitle() {
      return this.dialogType == "new"
        ? `新增${this.title}`
        : `编辑${this.title}`;
    },
  },
  components: {
    Pagination,
  },
  created() {
    this.getLetterList();
    this.getCaseList();
  },
  methods: {
    getLetterList() {
      this.listLoading = true;
      getLetters(this.listQuery)
        .then((res) => {
          this.letters = res.results;
          this.listLoading = false;
          this.total = res.count;
        })
        .catch((error) => {
          console.log(error);
          this.$message.error("获取律师函信息失败!");
          this.listLoading = false;
        });
    },
    getCaseList() {
      getAllCases().then((res) => {
        this.cases = res;
      });
    },
    dataFormatter(row, column, cellValue, index) {
      if (column.property == "apply_time") {
        return formatDateTime(cellValue);
      } else if (column.property == "stamp_time") {
        return formatDateTime(cellValue);
      } else {
        return cellValue;
      }
    },
    // 查询
    handleFilter() {
      this.listQuery.page = 1;
      this.getLetterList();
    },
    caseChange(selVal) {
      const index = this.cases.findIndex((v) => {
        return v.id === selVal;
      });

      if (index == -1) return;
      const sel_case = this.cases[index];
      this.form.party = sel_case.party;
      this.form.client = sel_case.client;
      let lawyer = sel_case.lead_lawyer_name;
      if (
        sel_case.assist_lawyer_name &&
        sel_case.assist_lawyer_name.length > 0
      ) {
        lawyer += "、" + sel_case.assist_lawyer_name;
      }
      this.form.lawyer = lawyer;
      this.form.court = "";
      this.form.reason = sel_case.reason;
      this.form.case_type = sel_case.case_type;
      this.form.level = sel_case.level;

      this.case_type = sel_case.case_type;
      console.log(this.cases[index]);
    },
    // 增加
    handleAdd() {
      this.form = Object.assign({}, defaultForm);

      this.dialogType = "new";
      this.dialogVisible = true;

      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 修改用户
    handleEdit(scope) {
      this.form = Object.assign({}, scope.row);
      this.dialogType = "edit";

      this.case_type = scope.row.case_type;

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 删除用户
    handleDelete({ $index, row }) {
      this.$confirm("确定要删除该案件吗?", "删除提示：", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await delLetter(row.id);
          this.letters.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 保存操作
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        const apply_confirm = this.form.apply_confirm;
        if (flag) {
          if (apply_confirm == false) {
            this.$message.error("申请确认请选择确定,才能打印");
            return;
          }
        }
        const isEdit = this.dialogType === "edit";
        let res = null;
        if (isEdit) {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          res = await updateLetter(this.form);
          const index = this.letters.findIndex((v) => v.id === res.id);
          this.letters.splice(index, 1, res);
        } else {
          this.form.user = this.uid;
          res = await addLetter(this.form);
          const { id } = res;
          if (id > 0) {
            this.letters.unshift(res);
          }
        }

        const { client, party, lawyer } = this.form;
        if (flag) {
          this.$router.push(`/case/civil_print/${res.id}`);
          return;
        } else {
          this.dialogVisible = false;
        }

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>委托人: ${client}</div>
              <div>当事人: ${party}</div>
              <div>电话: ${lawyer}</div>
            `,
          type: "success",
        });
      });
    },
    handlePrint(data) {
      this.$router.push(`/case/civil_print/${data.id}`);
    },
  },
};
</script>

<style lang='scss' scoped>
// .app-container {
//   // .el-table {
//   //   margin-top: 10px;
//   //   width: 100%;
//   // }
// }
</style>